package es

import (
	"context"
	"fmt"
	"os"

	"github.com/olivere/elastic/v7"
	log "github.com/sirupsen/logrus"
)

//ES客户端
var EsClient *elastic.Client

//初始化es连接
func init() {
	EsClient = GetEsClient()
}

//获取连接
func GetEsClient() *elastic.Client {
	ctx := context.Background()

	// Obtain a client and connect to the default Elasticsearch installation
	// on 127.0.0.1:9200. Of course you can configure your client to connect
	// to other hosts and configure it in various other ways.
	client, err := elastic.NewClient(elastic.SetURL(os.Getenv("ESURL")), elastic.SetSniff(false))
	if err != nil {
		// Handle error
		log.Error(err)
		panic(err)
	}
	fmt.Println(os.Getenv("ESURL"))
	// Ping the Elasticsearch server to get e.g. the version number
	info, code, err := client.Ping(os.Getenv("ESURL")).Do(ctx)
	if err != nil {
		// Handle error
		log.Error(err)
		panic(err)
	}
	fmt.Printf("Elasticsearch returned with code %d and version %s\n", code, info.Version.Number)

	return client
}
